package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BusinessException;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    /**
     * 套餐新增
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void add(SetmealDTO setmealDTO) {
        //1. 保存套餐
        Setmeal setmeal = BeanUtil.copyProperties(setmealDTO, Setmeal.class);
        setmeal.setStatus(1);
        setmealMapper.insert(setmeal);
        //2. 保存套餐菜品
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(setmealDishes == null || setmealDishes.size() < 1){
            throw new BusinessException(400,"套餐必须关联菜品");
        }
        //2.1. 遍历套餐菜品，关联套餐id
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
        });

        //2.2. 批量保存套餐菜品
        setmealDishMapper.batchInsert(setmealDishes);
    }

    /**
     * 套餐分页查询
     * @param setmealPageDTO
     * @return
     */
    @Override
    public PageResult page(SetmealPageDTO setmealPageDTO) {
        //1. 开启分页
        PageHelper.startPage(setmealPageDTO.getPage(),setmealPageDTO.getPageSize());
        //2. 查询
        List<SetmealVO> pageList = setmealMapper.pageList(setmealPageDTO);
        //3. 封装结果
        PageInfo<SetmealVO> pageInfo = new PageInfo<>(pageList);
        //4. 封装自定义分页对象
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 根据分类id查询套餐列表
     * @param setmealDTO
     * @return
     */
    @Override
    public List<Setmeal> paramList(SetmealDTO setmealDTO) {
        return setmealMapper.paramList(setmealDTO);
    }
}
